package com.coisini.service.impl;

import com.coisini.context.BaseContext;
import com.coisini.entity.AddressBook;
import com.coisini.mapper.AddressBookMapper;
import com.coisini.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        //设置当前用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }


    /**
     * 动态查询
     * @return
     */
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        return   addressBookMapper.list(addressBook);

    }

    /**
     *默认地址
     * 1.先将当前用户的所有地址改为非默认
     * 2.将当前地址修改为默认地址
     * @param addressBook
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        //1.先将当前用户所有地址设置为非默认
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultGetByUserId(addressBook);

        //2.在修改当前地址为默认
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }


    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
       AddressBook addressBook=  addressBookMapper.getById(id);
       return addressBook;
    }

    /**
     * 根据id修改地址
     */
    @Override
    public void updateById(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }
}
